import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
import math

data = np.loadtxt(r'./data/xigua.txt', delimiter=',')
np.random.seed(1)
np.random.shuffle(data)
m = len(data)
print(m)
print(data)

X = data[:, :-1]
y = data[:, -1]

scaler = StandardScaler()
X = scaler.fit_transform(X)

m_train = int(math.floor(0.7 * m))
X_train, X_test = np.split(X, [m_train])
y_train, y_test = np.split(y, [m_train])

clf = SVC(C=1, kernel='rbf', decision_function_shape='ovr', gamma=1)
clf.fit(X_train, y_train)
print(f'training score = {clf.score(X_train, y_train)}')
print(f'testing score = {clf.score(X_test, y_test)}')

plt.scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], zorder=500, s=1, c='r', label='pos')
plt.scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], zorder=500, s=1, c='b', label='neg')
plt.scatter(X_test[y_test == 1, 0], X_test[y_test == 1, 1], zorder=500, s=5, c='r', label='pos test')
plt.scatter(X_test[y_test == 0, 0], X_test[y_test == 0, 1], zorder=500, s=5, c='b', label='neg test')

xx, yy = np.mgrid[X[:, 0].min():X[:, 0].max():100j, X[:, 1].min():X[:, 1].max():100j]
xxyy = np.c_[xx.ravel(), yy.ravel()]
zz11 = clf.predict(xxyy).reshape(xx.shape)
plt.contourf(xx, yy, zz11, zorder=0, cmap=plt.cm.Paired)
zz = clf.decision_function(xxyy).reshape(xx.shape)
plt.contour(xx, yy, zz, zorder=10, levels=10)

plt.legend()
plt.show()
